package geektime.concurrent.part1;

/**
 * 模拟synchronized加锁对象的不同对结果的影响
 */
public class BadLockOnInteger implements Runnable {

    private static Integer i = 0;
    private static BadLockOnInteger instance = new BadLockOnInteger();

    @Override
    public void run() {
        // 这里的关键是要让不同的线程竞争同一把锁，如果synchronized()中使用i作为锁对象，就无法保证锁对象不变
        for (int j = 0; j < 500000; j++) {
            synchronized (instance) {
                i++;
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // 这里预期使用两个线程来各执行500000次的i++，让最终的i为1000000
        Thread thread1 = new Thread(instance);
        Thread thread2 = new Thread(instance);
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println(i);
    }
}
